package ru.ifmo.common.xml;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import ru.ifmo.common.Source;

import java.util.Collection;

/**
 * @author avhaliullin
 */
public class XmlCollectionExtractor<E, C extends Collection<E>> implements XmlObjectExtractor<C> {
    private final String tagElement;
    private final Source<C> collectionSource;
    private final XmlObjectExtractor<E> elementExtractor;

    public XmlCollectionExtractor(Source<C> collectionSource, String tagElement, XmlObjectExtractor<E> elementExtractor) {
        this.tagElement = tagElement;
        this.collectionSource = collectionSource;
        this.elementExtractor = elementExtractor;
    }

    public C extract(Element element) {
        C collectionInstance = collectionSource.create();
        NodeList statesList = element.getElementsByTagName(tagElement);
        for (Object node : XmlUtil.getNodeListIterable(statesList)) {
            Element elementOfCollection;
            if (node instanceof Element) {
                elementOfCollection = (Element) node;
                collectionInstance.add(elementExtractor.extract(elementOfCollection));
            }
        }
        return collectionInstance;
    }
}
